<?php

class LanguageViewFilter extends ViewFilter
{

  public function filter($output)
  {
    if (preg_match_all('/(<lang( .*?)?>(.*?)(?:<plural\/>(.*?))?<\/lang>)/im', $output, $m)) {
      foreach ($m[0] as $k => $v) {
        $params = array();
        if (preg_match_all('/([a-z]+)="([^"]*)"/im', $m[2][$k], $_params)) {
          foreach ($_params[0] as $_k => $_v) {
            $params[$_params[1][$_k]] = $_params[2][$_k];
          }
        }

        $s = $m[3][$k];

        $args = array(
          $s
        );

        if (! empty($m[4][$k])) {
          if (! isset($params['count'])) {
            throw new Exception('Missing count attribute in tag: <b>' . htmlentities($m[0][$k]) . '</b>');
          }

          $args[] = $m[4][$k];
          $args[] = $params['count'];

          if (isset($params['domain'])) {
            $args[] = sy_get_param($params, 'domain');
            $func = '_dn';
          }
          else {
            $func = '_n';
          }
        }

        else {
          if (isset($params['domain'])) {
            $args[] = sy_get_param($params, 'domain');
            $func = '_d';
          }
          else {
            $func = '__';
          }
        }

        $transl = call_user_func_array($func, $args);

        if (isset($params['args'])) {
          $sep = sy_get_param($params, 'argsep', '|');
          $fargs = explode($sep, $params['args']);
          array_unshift($fargs, $transl);
          $transl = call_user_func_array('sprintf', $fargs);
        }

        $output = str_replace($m[0][$k], $transl, $output);
      }
    }

    return $output;
  }

}

?>